/*
    ofxMailUtils
    author: arturo
*/

#include "ofxMailUtils.h"

// ----------------------------------------------------------------------
ofxSmtpClientUtils::ofxSmtpClientUtils(string _host, int _port, string _username, string _password, int _timeout){
	connected = false;
	try{
		/**
		 SecureStreamSocket mySocket( SocketAddress(host, port) );
		 session=new Poco::Net::SMTPClientSession( SecureStreamSocket( SocketAddress(host, port) ) );		 
		 */
		session=new Poco::Net::SMTPClientSession(_host, _port);
		if(_timeout != -1){
			Poco::Timespan timeout;
			timeout.assign(_timeout, 0);
			session->setTimeout(timeout);
		}
		
		if(_username != "" && _password != "")
			session->login(session->AUTH_LOGIN, _username, _password);
		else
			session->login();
		connected = true;
	}catch(Poco::Exception e){
		ofLog(OF_LOG_ERROR,"cannot connect to the server");
	}
}
// ----------------------------------------------------------------------
ofxSmtpClientUtils::~ofxSmtpClientUtils(){
    stop();
}
//-------------------------------
// non blocking functions
void ofxSmtpClientUtils::addMessage(ofxMailMessage* message){
	messages.push(message);
	if(!isThreadRunning())
		start();
}

//-------------------------------
// blocking functions
void ofxSmtpClientUtils::sendMessage(ofxMailMessage* message){
	if(connected)
		session->sendMessage(message->getPocoMessage());
	else
		ofLog(OF_LOG_ERROR,"cannot send, not connected to the smtp server");
}


// ----------------------------------------------------------------------
void ofxSmtpClientUtils::start() {
     if (isThreadRunning() == false){
        printf("smtp:thread started\n");
        startThread(true,true);
    }
}
// ----------------------------------------------------------------------
void ofxSmtpClientUtils::stop() {
    stopThread();
}
// ----------------------------------------------------------------------
void ofxSmtpClientUtils::threadedFunction(){

    // loop through this process whilst thread running
    while( isThreadRunning() == true ){
    	if(messages.size()){
			try{
				sendMessage(messages.front());
				messages.front()->sent = true;
			}catch(Poco::Exception e){
				cout << "sent message exception:" << e.displayText() << ":" << endl;
			}
    		messages.pop();
    	}else{
    		stop();
    	}

    }

}



